# -*- coding: utf-8 -*-
"""
用户系统模块 - 数据模型
"""

from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils import timezone


class User(AbstractUser):
    """
    用户模型 - 扩展Django自带的用户模型
    
    继承AbstractUser，包含username, email, password等基础字段
    额外添加了平台所需的个性化字段
    """
    
    # 基本信息字段
    phone = models.CharField(
        max_length=11, 
        unique=True, 
        null=True, 
        blank=True,
        verbose_name='手机号',
        help_text='用户手机号，用于注册和登录'
    )
    
    nickname = models.CharField(
        max_length=50,
        verbose_name='昵称',
        help_text='用户显示昵称'
    )
    
    avatar = models.ImageField(
        upload_to='avatars/%Y/%m/',
        blank=True,
        null=True,
        verbose_name='头像',
        help_text='用户头像（自动存储到MinIO云存储）'
    )
    
    signature = models.CharField(
        max_length=200,
        blank=True,
        verbose_name='个性签名',
        help_text='用户个性签名'
    )
    
    # 兴趣标签字段（以逗号分隔的标签字符串）
    interests = models.CharField(
        max_length=500,
        blank=True,
        verbose_name='兴趣标签',
        help_text='用户兴趣标签，多个标签用逗号分隔，如：运动,读书,旅游'
    )
    
    # 隐私设置（使用JSON字段实现细粒度控制）
    privacy_settings = models.JSONField(
        default=dict,
        verbose_name='隐私设置',
        help_text='''JSON格式的隐私配置，支持细粒度控制。
        默认结构：{
            "profile": {"nickname": true, "avatar": true, "phone": false, "email": false, "signature": true, "interests": true},
            "activity": {"created_activities": true, "joined_activities": true, "comments": true, "ratings": true},
            "social": {"following_list": true, "follower_list": true, "points": false}
        }'''
    )
    
    # 用户积分
    points = models.IntegerField(
        default=0,
        verbose_name='积分',
        help_text='用户当前积分总数'
    )
    
    # 第三方登录标识
    wechat_openid = models.CharField(
        max_length=100,
        unique=True,
        null=True,
        blank=True,
        verbose_name='微信OpenID',
        help_text='微信登录的唯一标识'
    )
    
    google_id = models.CharField(
        max_length=100,
        unique=True,
        null=True,
        blank=True,
        verbose_name='Google ID',
        help_text='Google登录的唯一标识'
    )
    
    facebook_id = models.CharField(
        max_length=100,
        unique=True,
        null=True,
        blank=True,
        verbose_name='Facebook ID',
        help_text='Facebook登录的唯一标识'
    )
    
    # 统计字段
    created_activities_count = models.IntegerField(
        default=0,
        verbose_name='创建活动数',
        help_text='用户创建的活动总数'
    )
    
    joined_activities_count = models.IntegerField(
        default=0,
        verbose_name='参与活动数',
        help_text='用户参与的活动总数'
    )
    
    # 时间戳
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='注册时间'
    )
    
    updated_at = models.DateTimeField(
        auto_now=True,
        verbose_name='更新时间'
    )
    
    class Meta:
        db_table = 'users'
        verbose_name = '用户'
        verbose_name_plural = '用户'
        ordering = ['-created_at']
    
    def __str__(self):
        return self.nickname or self.username
    
    def get_default_privacy_settings(self):
        """获取默认隐私设置"""
        return {
            "profile": {
                "nickname": True,
                "avatar": True,
                "phone": False,
                "email": False,
                "signature": True,
                "interests": True
            },
            "activity": {
                "created_activities": True,
                "joined_activities": True,
                "comments": True,
                "ratings": True
            },
            "social": {
                "following_list": True,
                "follower_list": True,
                "points": False
            }
        }
    
    def init_privacy_settings(self):
        """初始化隐私设置（用于新用户注册）"""
        if not self.privacy_settings:
            self.privacy_settings = self.get_default_privacy_settings()
            self.save()
    
    def is_field_public(self, category, field_name):
        """
        检查某个字段是否公开
        
        Args:
            category: 分类，如 'profile', 'activity', 'social'
            field_name: 字段名，如 'nickname', 'phone'
        
        Returns:
            bool: True表示公开，False表示私密
        """
        if not self.privacy_settings:
            self.privacy_settings = self.get_default_privacy_settings()
        
        try:
            return self.privacy_settings.get(category, {}).get(field_name, True)
        except (AttributeError, TypeError):
            return True  # 默认公开
    
    def update_privacy_setting(self, category, field_name, is_public):
        """
        更新单个隐私设置
        
        Args:
            category: 分类
            field_name: 字段名
            is_public: 是否公开
        """
        if not self.privacy_settings:
            self.privacy_settings = self.get_default_privacy_settings()
        
        if category not in self.privacy_settings:
            self.privacy_settings[category] = {}
        
        self.privacy_settings[category][field_name] = is_public
        self.save()
    
    def get_public_profile(self, viewer_user=None):
        """
        获取对外公开的用户资料
        
        Args:
            viewer_user: 查看者（可用于实现好友可见等逻辑）
        
        Returns:
            dict: 公开的用户信息
        """
        profile = {
            'id': self.id,
            'username': self.username,
        }
        
        # 根据隐私设置返回字段
        if self.is_field_public('profile', 'nickname'):
            profile['nickname'] = self.nickname
        
        if self.is_field_public('profile', 'avatar'):
            profile['avatar'] = self.avatar.url if self.avatar else None
        
        if self.is_field_public('profile', 'signature'):
            profile['signature'] = self.signature
        
        if self.is_field_public('profile', 'interests'):
            profile['interests'] = self.interests
        
        if self.is_field_public('profile', 'phone'):
            profile['phone'] = self.phone
        
        if self.is_field_public('profile', 'email'):
            profile['email'] = self.email
        
        # 统计信息
        if self.is_field_public('activity', 'created_activities'):
            profile['created_activities_count'] = self.created_activities_count
        
        if self.is_field_public('activity', 'joined_activities'):
            profile['joined_activities_count'] = self.joined_activities_count
        
        if self.is_field_public('social', 'points'):
            profile['points'] = self.points
        
        return profile


class UserFollow(models.Model):
    """
    用户关注关系模型
    
    记录用户之间的关注关系
    follower关注了following
    """
    
    follower = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='following_set',
        verbose_name='关注者',
        help_text='发起关注的用户'
    )
    
    following = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='follower_set',
        verbose_name='被关注者',
        help_text='被关注的用户'
    )
    
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='关注时间'
    )
    
    class Meta:
        db_table = 'user_follows'
        verbose_name = '用户关注'
        verbose_name_plural = '用户关注'
        unique_together = ('follower', 'following')
        ordering = ['-created_at']
    
    def __str__(self):
        return f"{self.follower.nickname} 关注了 {self.following.nickname}"


class PrivateMessage(models.Model):
    """
    私信模型
    
    用户之间的一对一私信功能
    """
    
    sender = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='sent_messages',
        verbose_name='发送者'
    )
    
    receiver = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='received_messages',
        verbose_name='接收者'
    )
    
    content = models.TextField(
        verbose_name='消息内容'
    )
    
    is_read = models.BooleanField(
        default=False,
        verbose_name='是否已读'
    )
    
    read_at = models.DateTimeField(
        null=True,
        blank=True,
        verbose_name='阅读时间'
    )
    
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='发送时间'
    )
    
    class Meta:
        db_table = 'private_messages'
        verbose_name = '私信'
        verbose_name_plural = '私信'
        ordering = ['-created_at']
    
    def __str__(self):
        return f"{self.sender.nickname} -> {self.receiver.nickname}: {self.content[:20]}"
